package com.ruoyi.web.controller.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TPayChannel;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.service.ITPayChannelService;
import com.ruoyi.business.service.ITRecipientInfoService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.MD5Util;
import com.ruoyi.common.utils.SignUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图标相关
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/demo/pay")
public class
DemoPayController
{
    private String prefix = "payment";
    @Autowired
    private ITPayChannelService tPayChannelService;

    @Autowired
    private ISysConfigService iSysConfigService;
    @Autowired
    private ITRecipientInfoService tRecipientInfoService;
    /**
     * FontAwesome图标
     */
    @GetMapping("/demo")
    public String demo()
    {
        return prefix + "/demo";
    }

    @GetMapping("/doc")
    public String doc()
    {
        return  "demo/doc/pay";
    }


    @PostMapping("/getChannel/{type}")
    @ResponseBody
    public AjaxResult getChannel(@PathVariable("type") String type)
    {
        TPayChannel tPayChannel = new TPayChannel();
        tPayChannel.setType(type);
        tPayChannel.setUserId(105L);
        List<TPayChannel> list = tPayChannelService.selectTPayChannelListByUser(tPayChannel);
        return AjaxResult.success(list);
    }

    @PostMapping("/getRecipientInfo/{channel}")
    @ResponseBody
    public AjaxResult getRecipientInfo(@PathVariable("channel") String channel)
    {
        TRecipientInfo tRecipientInfo = new TRecipientInfo();
        tRecipientInfo.setChannel(channel);
        tRecipientInfo.setAvailable(1);
        tRecipientInfo.setChannelDisabled(0);
        List<TRecipientInfo> list = tRecipientInfoService.selectTRecipientInfoList(tRecipientInfo);
        return AjaxResult.success(list);
    }

    @PostMapping("test/{channelCode}/{amount}/{realChannelCode}/{recipentId}")
    @ResponseBody
    public AjaxResult test(HttpServletRequest request, @PathVariable("channelCode") String channelCode, @PathVariable("amount") String amount, @PathVariable("realChannelCode") String realChannelCode, @PathVariable("recipentId") String recipentId
           ) throws ClientProtocolException, IOException {
        Map<String, String> params = new HashMap<String, String>();
        String ip = "";
        if (request.getHeader("x-forwarded-for") == null) {
            ip = request.getRemoteAddr();
        } else {
            ip = request.getHeader("x-forwarded-for");

        }
        String nginxPayGateway = iSysConfigService.selectConfigByKey("sys.bussine.nginxPayGateway");
        String orderCode = String.valueOf(new Date().getTime());
        params.put("channelType", channelCode);  //根据请求的支付类型不一样， 选择不同的支付方式
        params.put("channel", realChannelCode);
        params.put("nonce_str", orderCode);
        params.put("uid", "105");  //根据平台分配的merchantid, 替换配置
        params.put("outTradeNo", orderCode);   //商家系统的订单号， 请保持再商家系统里面唯一
        params.put("goodsName", "test");    //购买物品的名称
        params.put("money", amount);   //精确到小数点后两位
        params.put("recipientId", recipentId);   //精确到小数点后两位
        String url = nginxPayGateway + "/demo/pay/callback/" + orderCode;
        System.out.printf("回调地址=======" + url);
        params.put("notifyUrl", url);
        params.put("returnUrl", url);   //精确到小数点后两位
        params.put("timestamp", String.valueOf(new Date().getTime()));
//		params.put("card_no", "6226661700077532");
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        System.out.println("请求网关=======" + preStr + "&key=d2f94d8815eb48af9e1296772c82872a");
        String sign = MD5Util.stringMD5(preStr + "&key=d2f94d8815eb48af9e1296772c82872a");
        params.put("sign", sign.toUpperCase());

        StringBuilder newbuf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(newbuf, params, false);
        String newStr = newbuf.toString();
        System.out.println(newStr);
//        String result =  HttpUtils.sendPost(callBackIpAddress+"smartpayment/pay/gateway",newStr);
        String reqUrl = "";
        reqUrl = nginxPayGateway  + "/api/v1/charges";

        System.out.println("请求网关=======" + reqUrl);

        HttpPost httpPost = new HttpPost(reqUrl);
        StringEntity entity = new StringEntity(newStr, "utf-8");//解决中文乱码问题
        httpPost.setEntity(entity);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
//        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("110.73.45.159", 8123));

//        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(proxy);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        response = httpClient.execute(httpPost);

        //String responseContent = HttpUtils.sendPostByProxy(callBackIpAddress+"smartpayment/pay/gateway",newStr);

        System.out.println(response.getStatusLine().getStatusCode() + "\n");
        HttpEntity result = response.getEntity();
        String responseContent = EntityUtils.toString(result, "UTF-8");
        System.out.println(responseContent);
        JSONObject resultObj = JSONObject.parseObject(responseContent);
        if (resultObj.getString("code").equalsIgnoreCase("200")) {  //标识成功
            Map<String, String> respMap = JSON.parseObject(responseContent, Map.class);
            JSONObject data = resultObj.getJSONObject("data");
            return AjaxResult.success(data.getString("payUrl"));
        } else {
            //异常
            return AjaxResult.error(resultObj.getString("message"));
        }
    }

    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "callback/{orderCode}")
    @ResponseBody
    public String test(@PathVariable("orderCode") String orderCode,HttpServletRequest request) throws ClientProtocolException, IOException {
        System.out.printf("回调订单编码=======" + orderCode);
        BufferedReader br;
        StringBuilder sb = null;
        String reqBody = null;
        br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        reqBody = URLDecoder.decode(sb.toString(), "UTF-8");
//            body = URLDecoder.decode(body, "UTF-8").replace("}=", "}");
        System.out.printf("==采用流的方式獲取到的======" + reqBody);
        return "success";

    }

}
